[[...path]].page.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. import React from 'react';
  2. import { IUserHasId, IPagePopulatedToShowRevision } from '@growi/core';
  3. import {
  4. GetServerSideProps, GetServerSidePropsContext,
  5. } from 'next';
  6. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  7. import dynamic from 'next/dynamic';
  8. import Head from 'next/head';
  9. import superjson from 'superjson';
  10. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  11. import { MainPane } from '~/components/Layout/MainPane';
  12. import { ShareLinkLayout } from '~/components/Layout/ShareLinkLayout';
  13. import GrowiContextualSubNavigationSubstance from '~/components/Navbar/GrowiContextualSubNavigation';
  14. import RevisionRenderer from '~/components/Page/RevisionRenderer';
  15. import ShareLinkAlert from '~/components/Page/ShareLinkAlert';
  16. import type { PageSideContentsProps } from '~/components/PageSideContents';
  17. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  18. import type { ShareLinkPageContentsProps } from '~/components/ShareLink/ShareLinkPageContents';
  19. import { SupportedAction, SupportedActionType } from '~/interfaces/activity';
  20. import { CrowiRequest } from '~/interfaces/crowi-request';
  21. import { RendererConfig } from '~/interfaces/services/renderer';
  22. import { IShareLinkHasId } from '~/interfaces/share-link';
  23. import type { PageDocument } from '~/server/models/page';
  24. import { generateSSRViewOptions } from '~/services/renderer/renderer';
  25. import {
  26. useCurrentUser, useCurrentPageId, useRendererConfig, useIsSearchPage, useCurrentPathname,
  27. useShareLinkId, useIsSearchServiceConfigured, useIsSearchServiceReachable, useIsSearchScopeChildrenAsDefault, useDrawioUri, useIsContainerFluid,
  28. } from '~/stores/context';
  29. import loggerFactory from '~/utils/logger';
  30. import { NextPageWithLayout } from '../_app.page';
  31. import {
  32. CommonProps, getServerSideCommonProps, generateCustomTitleForPage, getNextI18NextConfig,
  33. } from '../utils/commons';
  34. const logger = loggerFactory('growi:next-page:share');
  35. const PageSideContents = dynamic<PageSideContentsProps>(() => import('~/components/PageSideContents').then(mod => mod.PageSideContents), { ssr: false });
  36. // const Comments = dynamic(() => import('~/components/Comments').then(mod => mod.Comments), { ssr: false });
  37. const ForbiddenPage = dynamic(() => import('~/components/ForbiddenPage'), { ssr: false });
  38. type Props = CommonProps & {
  39. shareLinkRelatedPage?: IShareLinkRelatedPage,
  40. shareLink?: IShareLinkHasId,
  41. isExpired: boolean,
  42. disableLinkSharing: boolean,
  43. isSearchServiceConfigured: boolean,
  44. isSearchServiceReachable: boolean,
  45. isSearchScopeChildrenAsDefault: boolean,
  46. drawioUri: string | null,
  47. rendererConfig: RendererConfig,
  48. };
  49. type IShareLinkRelatedPage = IPagePopulatedToShowRevision & PageDocument;
  50. superjson.registerCustom<IShareLinkRelatedPage, string>(
  51. {
  52. isApplicable: (v): v is IShareLinkRelatedPage => {
  53. return v != null
  54. && v.toObject != null
  55. && v.lastUpdateUser != null
  56. && v.creator != null
  57. && v.revision != null;
  58. },
  59. serialize: (v) => { return superjson.stringify(v.toObject()) },
  60. deserialize: (v) => { return superjson.parse(v) },
  61. },
  62. 'IShareLinkRelatedPageTransformer',
  63. );
  64. // GrowiContextualSubNavigation for shared page
  65. // get page info from props not to send request 'GET /page' from client
  66. type GrowiContextualSubNavigationForSharedPageProps = {
  67. currentPage?: IPagePopulatedToShowRevision,
  68. isLinkSharingDisabled: boolean,
  69. }
  70. const GrowiContextualSubNavigationForSharedPage = (props: GrowiContextualSubNavigationForSharedPageProps): JSX.Element => {
  71. const { currentPage, isLinkSharingDisabled } = props;
  72. if (currentPage == null) { return <></> }
  73. return (
  74. <div data-testid="grw-contextual-sub-nav">
  75. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  76. </div>
  77. );
  78. };
  79. const SharedPage: NextPageWithLayout<Props> = (props: Props) => {
  80. useCurrentPathname(props.shareLink?.relatedPage.path);
  81. useIsSearchPage(false);
  82. useShareLinkId(props.shareLink?._id);
  83. useCurrentPageId(props.shareLink?.relatedPage._id);
  84. useCurrentUser(props.currentUser);
  85. useRendererConfig(props.rendererConfig);
  86. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  87. useIsSearchServiceReachable(props.isSearchServiceReachable);
  88. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  89. useDrawioUri(props.drawioUri);
  90. useIsContainerFluid(props.isContainerFluid);
  91. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  92. const isNotFound = props.shareLink == null || props.shareLink.relatedPage == null || props.shareLink.relatedPage.isEmpty;
  93. const isShowSharedPage = !props.disableLinkSharing && !isNotFound && !props.isExpired;
  94. const shareLink = props.shareLink;
  95. const pagePath = props.shareLinkRelatedPage?.path ?? '';
  96. const revisionBody = props.shareLinkRelatedPage?.revision.body;
  97. const title = generateCustomTitleForPage(props, pagePath);
  98. // TODO: show SSR body
  99. // const rendererOptions = generateSSRViewOptions(props.rendererConfig, pagePath);
  100. // const ssrBody = <RevisionRenderer rendererOptions={rendererOptions} markdown={revisionBody ?? ''} />;
  101. const sideContents = shareLink != null
  102. ? <PageSideContents page={shareLink.relatedPage} />
  103. : <></>;
  104. // const footerContents = shareLink != null && isPopulated(shareLink.relatedPage.revision)
  105. // ? (
  106. // <>
  107. // <Comments pageId={shareLink._id} pagePath={shareLink.relatedPage.path} revision={shareLink.relatedPage.revision} />
  108. // </>
  109. // )
  110. // : <></>;
  111. const contents = (() => {
  112. const ShareLinkPageContents = dynamic<ShareLinkPageContentsProps>(
  113. () => import('~/components/ShareLink/ShareLinkPageContents').then(mod => mod.ShareLinkPageContents),
  114. {
  115. ssr: false,
  116. // TODO: show SSR body
  117. // loading: () => ssrBody,
  118. },
  119. );
  120. return <ShareLinkPageContents page={props.shareLinkRelatedPage} />;
  121. })();
  122. return (
  123. <>
  124. <Head>
  125. <title>{title}</title>
  126. </Head>
  127. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  128. <header className="py-0 position-relative">
  129. {isShowSharedPage
  130. && <GrowiContextualSubNavigationForSharedPage currentPage={props.shareLinkRelatedPage} isLinkSharingDisabled={props.disableLinkSharing} />}
  131. </header>
  132. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  133. <MainPane
  134. sideContents={sideContents}
  135. // footerContents={footerContents}
  136. >
  137. { props.disableLinkSharing && (
  138. <div className="mt-4">
  139. <ForbiddenPage isLinkSharingDisabled={props.disableLinkSharing} />
  140. </div>
  141. )}
  142. { (isNotFound && !props.disableLinkSharing) && (
  143. <div className="container-lg">
  144. <h2 className="text-muted mt-4">
  145. <i className="icon-ban" aria-hidden="true" />
  146. <span> Page is not found</span>
  147. </h2>
  148. </div>
  149. )}
  150. { (props.isExpired && !props.disableLinkSharing && shareLink != null) && (
  151. <div className="container-lg">
  152. <ShareLinkAlert expiredAt={shareLink.expiredAt} createdAt={shareLink.createdAt} />
  153. <h2 className="text-muted mt-4">
  154. <i className="icon-ban" aria-hidden="true" />
  155. <span> Page is expired</span>
  156. </h2>
  157. </div>
  158. )}
  159. {(isShowSharedPage && shareLink != null) && (
  160. <>
  161. <ShareLinkAlert expiredAt={shareLink.expiredAt} createdAt={shareLink.createdAt} />
  162. <div className="mb-5">
  163. { contents }
  164. </div>
  165. </>
  166. )}
  167. </MainPane>
  168. </div>
  169. </>
  170. );
  171. };
  172. SharedPage.getLayout = function getLayout(page) {
  173. return (
  174. <>
  175. <DrawioViewerScript />
  176. <ShareLinkLayout>{page}</ShareLinkLayout>
  177. </>
  178. );
  179. };
  180. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  181. const req: CrowiRequest = context.req as CrowiRequest;
  182. const { crowi } = req;
  183. const { configManager, searchService, xssService } = crowi;
  184. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  185. props.isSearchServiceConfigured = searchService.isConfigured;
  186. props.isSearchServiceReachable = searchService.isReachable;
  187. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  188. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  189. props.rendererConfig = {
  190. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  191. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  192. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  193. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  194. plantumlUri: process.env.PLANTUML_URI ?? null,
  195. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  196. // XSS Options
  197. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  198. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  199. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  200. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  201. highlightJsStyleBorder: configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  202. };
  203. }
  204. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  205. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  206. props._nextI18Next = nextI18NextConfig._nextI18Next;
  207. }
  208. function getAction(props: Props): SupportedActionType {
  209. let action: SupportedActionType;
  210. if (props.isExpired) {
  211. action = SupportedAction.ACTION_SHARE_LINK_EXPIRED_PAGE_VIEW;
  212. }
  213. else if (props.shareLink == null) {
  214. action = SupportedAction.ACTION_SHARE_LINK_NOT_FOUND;
  215. }
  216. else {
  217. action = SupportedAction.ACTION_SHARE_LINK_PAGE_VIEW;
  218. }
  219. return action;
  220. }
  221. async function addActivity(context: GetServerSidePropsContext, action: SupportedActionType): Promise<void> {
  222. const req: CrowiRequest = context.req as CrowiRequest;
  223. const parameters = {
  224. ip: req.ip,
  225. endpoint: req.originalUrl,
  226. action,
  227. user: req.user?._id,
  228. snapshot: {
  229. username: req.user?.username,
  230. },
  231. };
  232. await req.crowi.activityService.createActivity(parameters);
  233. }
  234. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  235. const req = context.req as CrowiRequest<IUserHasId & any>;
  236. const { crowi, params } = req;
  237. const result = await getServerSideCommonProps(context);
  238. if (!('props' in result)) {
  239. throw new Error('invalid getSSP result');
  240. }
  241. const props: Props = result.props as Props;
  242. try {
  243. const ShareLinkModel = crowi.model('ShareLink');
  244. const shareLink = await ShareLinkModel.findOne({ _id: params.linkId }).populate('relatedPage');
  245. if (shareLink != null) {
  246. props.shareLinkRelatedPage = await shareLink.relatedPage.populateDataToShowRevision();
  247. props.isExpired = shareLink.isExpired();
  248. props.shareLink = shareLink.toObject();
  249. }
  250. }
  251. catch (err) {
  252. logger.error(err);
  253. }
  254. injectServerConfigurations(context, props);
  255. await injectNextI18NextConfigurations(context, props);
  256. await addActivity(context, getAction(props));
  257. return {
  258. props,
  259. };
  260. };
  261. export default SharedPage;